<template>
  <!-- 查询框 -->
  <!-- 根据角色的名字进行模糊查询 -->
  <el-input v-model="rname" style="width: 240px" placeholder="请输入名字"/>
  <el-button :icon="Search" circle @click="this.queryTableData()"/>

  <!-- 添加按钮 -->
  <el-button type="success" @click="addRole()">添加</el-button>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="id" label="Date" width="150"/>
    <el-table-column prop="rname" label="角色的名字" width="150"/>
    <el-table-column prop="rcode" label="角色编码" width="150"/>
<!--    <el-table-column prop="isdeleted" label="是否删除" width="120"/>-->
    <el-table-column label="状态" width="120">

      <template #default="scope">
        <el-switch
            v-model="scope.row.isdeleted"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            :active-value=0
            :inactive-value=1
            disabled
        >
<!--            @change="handleSwitchChange(scope.row)">-->
        </el-switch>
      </template>
    </el-table-column>

    <el-table-column label="Operations" min-width="120">
      <!-- scope代表的是当前的表格 -->
      <template #default="scope">
        <el-button v-if="scope.row.rcode!='ADMIN'" link type="primary" size="small" @click="handleClick(scope.row.id)">
          删除
        </el-button>
        <el-button v-if="scope.row.rcode!='ADMIN'" link type="primary" size="small"  @click="updRole(scope.row)">修改</el-button>

        <el-button v-if="scope.row.rcode!='ADMIN'" link type="primary" size="small"  @click="fenpei(scope.row)">权限分配</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!--  分页开始 -->
  <div class="demo-pagination-block">

    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[2, 4, 6, 8]"

        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 分页结束 -->


  <!--  模态框开始 -->
  <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="500"
      :before-close="handleClose"
  >
    <span>

       <!-- 模态框中的内容开始 -->

       <el-form
           ref="ruleFormRef"
           style="max-width: 600px"
           :model="ruleForm"
           :rules="rules"
           label-width="auto"
           class="demo-ruleForm"
           :size="formSize"
           status-icon
       >
    <el-form-item label="角色名字" prop="rname">
      <el-input v-model="ruleForm.rname"/>
    </el-form-item>
    <el-form-item label="角色编码" prop="rcode">
      <el-input v-model="ruleForm.rcode"/>
    </el-form-item>
   
    <el-form-item label="删除" prop="isdeleted">
<!--       0  代表没有删除  false-->
<!--      1 代表删除 true-->

<!--      <el-switch v-model="ruleForm.isdeleted"/>-->
      <el-switch
          v-model="ruleForm.isdeleted"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          :active-value="0"
          :inactive-value="1"
      />
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleFormRef')">
        提交
      </el-button>
      <el-button @click="resetForm('ruleFormRef')">取消</el-button>
    </el-form-item>
  </el-form>

      <!-- 模态框中的内容结束 -->
    </span>

  </el-dialog>

  <!-- 模态框结束 -->

<!--分配权限的模态框开始-->
  <!--  模态框开始 -->
  <el-dialog
      v-model="treedialogVisible"
      :title="treetitle"
      width="500"

  >
    <span>

<!--   模态框中的内容开始
         :default-expanded-keys="[2, 3]"
              :default-checked-keys="[5]"

 -->
      <el-tree
          ref="treeRef"
          style="max-width: 600px"
          :data="treedata2"
          show-checkbox
          node-key="id"
          default-expand-all

          :props="defaultProps"
      />

      <!-- 模态框中的内容结束 -->
    </span>

    <el-button type="primary" @click="tijiao()">
      提交
    </el-button>
    <el-button @click="this.treedialogVisible=false">取消</el-button>

  </el-dialog>


  <!--分配权限的模态框结束  -->

</template>

<script>
// 前后端交互   axios
import {
  Search
} from '@element-plus/icons-vue';
// import axios from 'axios';
import {ElMessage, ElMessageBox} from 'element-plus';

export default {
  computed: {
    Search() {
      return Search
    }
  },
  data() {
    return {
      ruleForm: {
        rname: "",
        rcode: "",
        isdeleted: 0,

      },
      rules: {
        // 规则
        rname: [
          {required: true, message: '请填写名字', trigger: 'blur'},
          {min: 3, max: 5, message: '字符串的长度在3-5之间', trigger: 'blur'},
        ],
        rcode: {required: true, message: '请填写角色编码', trigger: 'blur'},
      },
      title: "添加角色",
      // 模态框是否弹出
      dialogVisible: false,
      tableData: [],
      currentPage: 1,
      pageSize: 2,
      total: 100,
      rname: "",
      treedialogVisible:false,
      treetitle: "分配菜单权限",
      treedata2: [],

      defaultProps:{
        children: 'childMenus',
        label: 'mname',
      },
      rid:""

    }
  },
  methods: {

    // 提交分配的权限
    tijiao(){
      // 获取所有的半选节点
      let halfVal=this.$refs.treeRef.getHalfCheckedKeys();
      let fullval=this.$refs.treeRef.getCheckedKeys();
      let checkval=[...halfVal,...fullval];
     let myval= checkval.toString();
      // 角色的id
     // alert("角色的id:"+this.rid);

      this.$axios.get(`/tab-role-menu/updPre?rid=${this.rid}&mids=${myval}`).then(res=>{
        if(res.data.code==200){
          //
          alert("修改成功");
          this.treedialogVisible=false;
        }
      })

     // 选中的所有的菜单的id checkval


      // 获取所有的全选节点

    },
    // 分配权限
    fenpei(obj){
      this.rid=obj.id;
      //alert("角色的id:"+obj.id);
      this.treedialogVisible=true;

      // 降之前选中的清空

      this.$nextTick(() => {
        //this.$refs.treeRef.setChecked([], false, false);

        this.treedata2.forEach(item=>{
          this.$nextTick(() => {
            this.$refs.treeRef.setChecked(item.id, false, true);
          })
        })
      })

      // 得到当前的角色的id
      // 根据当前的角色的id 查询拥有的菜单的id
      this.$axios.get(`/tab-role-menu?rid=${obj.id}`).then(res=>{
        //console.log(res.data.data);
        //alert(JSON.stringify(res.data.data));
        //

        res.data.data.forEach(item=>{
         // alert(item.mid);
          this.$nextTick(() => {
            this.$refs.treeRef.setChecked(item.mid, true, false);
          })
        })

      })

    },

// 修改:
    updRole(obj){
      // obj 对象  一行的数据
      this.dialogVisible=true;
      //console.log(obj);
      this.title="修改角色";


      // 深拷贝
      this.ruleForm=JSON.parse(JSON.stringify(obj));;



    },


    // 提交表单
    // 校验通过之后 才可以提交
    submitForm(formName) {

      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 把数据提交到数据库里面   controller
          // 添加 post请求

          alert(JSON.stringify(this.ruleForm));
          // axios 发出一个post请求
          this.$axios.post("/tab-role",this.ruleForm).then(res=>{
            ElMessage({
              type: 'success',
              message: '添加成功',
            })

            // 关闭当前的模态框
            this.dialogVisible=false;
            this.queryTableData();

          })

        } else {
         alert('error submit!!');
          return false;
        }
      });


  },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 添加角色
    addRole() {
      //alert("弹出一个form表单");
      // dialogVisible 设置为true
      this.dialogVisible = true;
      this.ruleForm={
        rname: "",
        rcode: "",

        isdeleted: 0,
      }
    },


    // 页数发生更改
    handleCurrentChange(val) {

      //alert(`当前的的页数:${val}`)
      this.currentPage = val;
      this.queryTableData();
    },
    handleClick(id) {
      // alert(id);


      ElMessageBox.confirm(
          '您确定要删除吗',
          '警告',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            // alert(obj.row.id)
            // 后台请求删除
            this.$axios.delete("/tab-role?id=" + id).then(res => {
              // alert(res.data.code);
              // 刷新页面
              this.queryTableData();
              ElMessage({
                type: 'success',
                message: '删除成功',
              })

            })


          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: 'Delete canceled',
            })
          })

    },
    handleSizeChange(val) {
      // alert(`每页显示的条数是:${val}`)
      this.pageSize = val;
      this.queryTableData();
    },
    queryTableData() {
      this.$axios.get("/tab-role?currPage=" + this.currentPage + "&pageSize=" + this.pageSize + "&rname=" + this.rname).then(res => {

        // res.data.data
        this.tableData = res.data.data.records;
        // 一共有多少条数据
        console.log("数据的总条数：", res.data.data.total)
        this.total = res.data.data.total;
      })
    },
    queryTreeData(){
      this.$axios.get("/tab-menu").then(res=>{
        this.treedata2=res.data.data;
        console.log(this.treedata2)
      })
    }

  },
  created() {

    this.queryTableData();
    this.queryTreeData();

  },
}


</script>